package com.ytrsoft.service;

import com.ytrsoft.entity.BaseEntity;
import com.ytrsoft.repository.BaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public abstract class BaseService<T extends BaseEntity> {

    protected final BaseRepository<T> baseRepository;

    public BaseService(BaseRepository<T> baseRepository) {
        this.baseRepository = baseRepository;
    }

    @Transactional
    public T create(T entity) {
        return baseRepository.save(entity);
    }

    @Transactional(readOnly = true)
    public T findById(String id) {
        return baseRepository.findById(id).orElse(null);
    }

    @Transactional(readOnly = true)
    public List<T> findAll() {
        return baseRepository.findAll();
    }

    @Transactional(readOnly = true)
    public Page<T> findAll(Pageable pageable) {
        return baseRepository.findAll(pageable);
    }

    @Transactional(readOnly = true)
    public List<T> findAll(Specification<T> specification) {
        return baseRepository.findAll(specification);
    }

    @Transactional
    public T update(T entity) {
        return baseRepository.save(entity);
    }

    @Transactional
    public T delete(String id) {
        T entity = baseRepository.findById(id).orElse(null);
        if (entity != null && !entity.getDeleted()) {
            entity.setDeleted(Boolean.TRUE);
            baseRepository.save(entity);
        }
        return entity;
    }
}
